<?php

namespace App\Http\Model;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;


/**
 * 用户的钱包数据, 此处设计没有遵循封闭原则, 有时间要优化调, 整合到 FinanceCharm、FinanceDianond、FinanceWealth
 * Class FinanceUserWallet
 * @package App\Http\Model
 */
class FinanceUserWallet extends Base
{
    protected $table = 'finance_wallet';

    protected $gift_bag = 'gift_bag';
    private $redis_cache_finance_user_wallet = "CACHE:FINANCE:USER:WALLET";
    protected $statCon = 'statistics';
    protected $stat_remain = 'stat_remain';

    public $timestamps = false;
    public function __construct(array $attributes = [])
    {
        parent::__construct($this->table, $attributes);
    }



    /**
     * 初始化财富值
     * @param $user_id
     * @return bool
     */
    public function add_wallet($user_id){
        $data = [
            'user_id' => $user_id
        ];
        $result = DB::table($this->table)->insertGetId($data);
        return $result;
    }


    public function delWalletCache($userId){
        return Redis::DEL($this->redis_cache_finance_user_wallet . ':' . $userId);
    }

    /**
     * 获取用户钱包数据
     * @param $user_id
     * @return array
     */
    public function get_wallet($user_id){
        $key = $this->redis_cache_finance_user_wallet . ':' . $user_id;
        if (!Redis::exists($key)){
            $wallet = DB::table($this->table)->select('user_id',
                'diamond_balance',
                'charm_balance',
                'wealth_balance',
                'kk_balance',
                'charm_to_kk',
                'pearl_balance',
                'reputation_balance',
                'celebrity_balance',
                'jd_balance',
                'game_balance',
                'agent_jd_balance',
                'debris_balance',
                'energy',
                'energy_coin',
                'forest',
                'hc_balance')->where(['user_id'=>$user_id])->first();

            $result = self::objToArray($wallet);
            Redis::SET($this->redis_cache_finance_user_wallet . ':' . $user_id, json_encode($result), 'EX', 3600);
            return $result;
        }

        $cache_data = Redis::get($key);
        if (!empty($cache_data)){
            $result = json_decode($cache_data, true);
            if (!isset($result['pearl_balance'])) {
                $result['pearl_balance'] = 0;
            }
            if (!isset($result['reputation_balance'])) {
                $result['reputation_balance'] = 0;
            }
            if (!isset($result['celebrity_balance'])) {
                $result['celebrity_balance'] = 0;
            }
            if (!isset($result['hc_balance'])) {
                $result['hc_balance'] = 0;
            }
            if (!isset($result['jd_balance'])) {
                $result['jd_balance'] = 0;
            }
            if (!isset($result['game_balance'])) {
                $result['game_balance'] = 0;
            }
            if (!isset($result['agent_jd_balance'])) {
                $result['agent_jd_balance'] = 0;
            }
            if (!isset($result['debris_balance'])) {
                $result['debris_balance'] = 0;
            }
            if (!isset($result['energy'])) {
                $result['energy'] = 0;
            }
            if (!isset($result['energy_coin'])) {
                $result['energy_coin'] = 0;
            }
            if (!isset($result['forest'])) {
                $result['forest'] = 0;
            }

            return $result;
        }
    }

    /**
     * 获取用户钱包数据
     * @param $list_user_id 数组[0,1,2,3]
     * @return array
     */
    public function get_wallets($list_user_id){
        if (empty($list_user_id)){
            return [];
        }
        $data = Redis::MGET(array_map(function ($userId){
            return $this->redis_cache_finance_user_wallet . ':' . $userId;
        }, $list_user_id));

        $data_count = count($data);
        for ($i = 0; $i < $data_count; $i++){
            if (!empty($data[$i])){
                $itemData = json_decode($data[$i], true);
                if (!isset($itemData['pearl_balance'])) {
                    $itemData['pearl_balance'] = 0;
                }
                if (!isset($itemData['reputation_balance'])) {
                    $itemData['reputation_balance'] = 0;
                }
                if (!isset($itemData['celebrity_balance'])) {
                    $itemData['celebrity_balance'] = 0;
                }
                if (!isset($itemData['hc_balance'])) {
                    $itemData['hc_balance'] = 0;
                }
                if (!isset($itemData['jd_balance'])) {
                    $itemData['jd_balance'] = 0;
                }
                if (!isset($itemData['game_balance'])) {
                    $itemData['game_balance'] = 0;
                }
                if (!isset($itemData['agent_jd_balance'])) {
                    $itemData['agent_jd_balance'] = 0;
                }
                if (!isset($itemData['debris_balance'])) {
                    $itemData['debris_balance'] = 0;
                }
                if (!isset($itemData['energy'])) {
                    $itemData['energy'] = 0;
                }
                if (!isset($itemData['energy_coin'])) {
                    $itemData['energy_coin'] = 0;
                }
                if (!isset($itemData['forest'])) {
                    $itemData['forest'] = 0;
                }

                $data[$i] = $itemData;
                unset($list_user_id[$i]);
            }
            else{
                unset($data[$i]);
            }
        }
        if (empty($list_user_id)){
            return array_values($data);
        }
        $wallets = DB::table($this->table)
            ->whereIn('user_id', $list_user_id)
            ->get([
                'user_id',
                'diamond_balance',
                'charm_balance',
                'wealth_balance',
                'kk_balance',
                'charm_to_kk',
                'pearl_balance',
                'reputation_balance',
                'celebrity_balance',
                'jd_balance',
                'game_balance',
                'agent_jd_balance',
                'debris_balance',
                'energy',
                'energy_coin',
                'forest',
                'hc_balance'
            ]);
        $result = self::objToArray($wallets);
        for ($i = 0; $i < count($result); $i++){
            array_push($data, $result[$i]);
            Redis::SET($this->redis_cache_finance_user_wallet . ':' . $result[$i]['user_id'], json_encode($result[$i]), 'EX', 3600);
        }
        return array_values($data);
    }

    /**
     * 校验验证码
     * */
    public function checkSmsCode($phone,$smsCode){
        $smsCacheCode = Redis::get('sms_' . $phone);
        if ($smsCacheCode != $smsCode) {
            return false;
        }
        return true;
    }

    /**
     * 根据变更时间 查询用户资产数据
     *
     * @param int $changeTimestamp 变更时间戳
     * @return array
     * */
    public function getWalletsByChangeTimestamp($changeTimestamp)
    {
        $wallets = DB::table($this->table)
            ->where([['change_timestamp','>',$changeTimestamp]])
            ->orderBy('change_timestamp','asc')
            ->get([
                'user_id',
                'charm_balance',
                'wealth_balance',
                'reputation_balance',
                'celebrity_balance',
            ]);
        return self::objToArray($wallets);
    }

    /**
     * 根据变更时间 查询用户资产数据
     * */
    public function getUserWalletDiamond($userId)
    {
        $wallet = DB::table($this->table)->select('user_id','diamond_balance')->where('user_id', $userId)->first();
        $wallet = self::objToArray($wallet);
        $num = empty($wallet['diamond_balance']) ? 0 : $wallet['diamond_balance'];

        return (int) $num;
    }
    /**
     * 根据变更时间 查询所有用户总钻石数，金币数
     * */
    public function getUserWalletCount()
    {
        $timeStr=time();
        $wallet = DB::table($this->table) ->selectRaw('sum(diamond_balance) as diamond_count,sum(kk_balance) as kk_balance_count')->first();
        $wallet = self::objToArray($wallet);
        $gift_bag = DB::table('gift_bag as a')
            ->leftJoin('gift_library as b' ,'a.gift_id','=','b.gift_id')
            ->where('a.avail', '>', 0)
            ->selectRaw('sum(avail*price) as bag_diamond_num')
            ->first();
        $gift_bag = self::objToArray($gift_bag);
        $data = [
            'created_date' => date("Y-m-d", $timeStr),
            'type' => 1,
            'useDiamondAll' => $wallet['diamond_count'],
            'useKkBalanceAll' => $wallet['kk_balance_count'],
            'useBagGiftAll' => $gift_bag['bag_diamond_num'],
        ];
        $log = DB::connection($this->statCon)->table($this->stat_remain)
            ->where('created_date', date("Y-m-d", $timeStr))
            ->where('type', 1)
            ->first();
        if (empty($log)) {
            $id = DB::connection($this->statCon)->table($this->stat_remain)->insertGetId($data);
            if (empty($id)) {
                write_log("error_stat_remain", "stat_remain 新增失败", $data);
            }
        } else {
            DB::connection($this->statCon)->table($this->stat_remain)
                ->where('id', $log->id)->update($data);

        }
    }
}